package v5

import (
	"github.com/boltdb/bolt"
	"log"
)

// 定义一个迭代器来顺序打印区块链里面的内容,用bolt自带的foreach打印是没有顺序的,不是按照我们存储的顺序来打印的
type BlockChainIterator struct {
	//数据库
	DB *bolt.DB
	//当前指向hash指针
	CurrentPrint []byte
}

func (bc *BlockChain) NewBlockChainIterator() *BlockChainIterator {
	return &BlockChainIterator{
		DB: bc.DB,
		//首次指向最后一个hash值
		CurrentPrint: bc.TailHash,
	}
}

func (bci *BlockChainIterator) Next() *Block {
	var blockRes *Block
	bci.DB.View(func(tx *bolt.Tx) error {
		bucket := tx.Bucket([]byte(GetConst_blockChainDB_Bucket()))
		if bucket == nil {
			log.Panic("桶不存在,不能添加区块!")
			return nil
		}
		bytes := bucket.Get(bci.CurrentPrint)
		if bytes == nil {
			log.Panic("根据hash未找到数据")
			return nil
		}
		block := Deserialize(bytes)
		blockRes = block
		//hash前移动
		bci.CurrentPrint = block.PreHash
		return nil
	})
	return blockRes
}
